"use strict"

/**
 * index controller 
 * 
 */

var q = require("q");
var dateFormat = require('dateformat');
require('date-utils');
var db = require("../db");
var indexer = require("../index");

var indexHandler = {
    index: function (req, res) {
        var pg = req.query.p || 1;
        var limit = req.query.l || 20;
        var text = req.query.text || "";
        var src = req.query.source || "全部";
        var day = req.query.day || "0";
        var qurl = "index?l=" + limit;
        //title:(税务 地税 国税 地方税务 国家税务 随机 案源 稽查 查账) AND create_time:[2016-11-12 TO 2016-11-20] AND source: 安徽省政府采购网
        var queryTerm = {};
        if (text != "") {
            qurl += "&text=" + encodeURIComponent(text);
            queryTerm.title = text;
        } else {
            queryTerm.title = "*";
        }
        if (src != "" && src != "全部") {
            qurl += "&source=" + encodeURIComponent(src);
            queryTerm.source = "\"" + src + "\"";
        }
        if (day != "" && day != "0") {
            qurl += "&day=" + day;
            var now = new Date();
            var startDay = indexer.getBeforeDate(parseInt(day));
            queryTerm.create_time = {
                start: startDay,
                end: now,
                field: "create_time"
            };

        }

        var start = (pg - 1) * limit;

        var defer = q("");
        defer.then(function () {
            var d = q.defer();
            indexer.query(queryTerm, start, limit, function (err, data) {
                if (err) {
                    console.error(err);
                }
                var total = 0;
                var recs = [];
                if (data) {
                    total = data.response.numFound;
                    recs = data.response.docs;
                    for (var i = 0, j = recs.length; i < j; i++) {
                        var rec = recs[i];
                        var c_t = rec["create_time"] || null;
                        if (c_t) {
                            var dt = new Date(c_t);
                            dt.add({"hour": 8});
                            rec.create_time = dateFormat(dt, "yyyy-mm-dd hh:MM TT");
                        }
                    }
                }
                //page information build
                var pc = parseInt((parseInt(total) + (limit - 1)) / limit);
                var pgs = [];
                var pg_start = 1;
                if (pg > 5) {
                    pg_start = pg - 5;
                }

                var pg_end = pg_start + 10

                if (pg_end > pc) {
                    pg_end = pc;
                }

                for (var i = pg_start; i <= pg_end; i++) {
                    var pg_item = {};
                    pg_item.active = i == pg;
                    pg_item.url = qurl + "&p=" + i;
                    pg_item.text = i;
                    pgs.push(pg_item);
                }
                //page information build end.

                var renderObj = {
                    items: recs,
                    text: text,
                    source: src,
                    pgs: pgs,
                    firsturl: qurl + "&p=1",
                    lasturl: qurl + "&p=" + pc,
                    total: total,
                    day: day
                };
                d.resolve(renderObj);
            });
            return d.promise;
        }).then(function (renderObject) {
            var d = q.defer();
            var sql = "select distinct source as source from items";
            db.query(sql, function (err, recs) {
                var srcs = [{ name: "全部", index: "" }];
                if (err) {
                    console.log("select distinct source is faild");
                } else {
                    recs.forEach(function (rec, idx) {
                        srcs.push({ name: rec["source"], index: idx + 1 });
                    });
                }
                renderObject.sources = srcs;
                res.render("index", renderObject);
            });
            return d.promise;
        });
    }
};

exports = module.exports = {
    "/": indexHandler.index,
    "/index": indexHandler.index
};